<template>
  <div class="post-integrated-container">    <div class="post-list-header">
      <h2>发帖讨论区</h2>
      <div class="tab-group">
        <button :class="{active: tab==='all'}" @click="switchTab('all')">全部帖子</button>
        <button :class="{active: tab==='like'}" @click="switchTab('like')">我点赞的</button>
        <button :class="{active: tab==='fav'}" @click="switchTab('fav')">我收藏的</button>
        <button :class="{active: tab==='comment'}" @click="switchTab('comment')">我评论的</button>
      </div>
      <button class="post-btn" @click="togglePostForm">
        <span class="btn-icon">{{ isPostFormVisible ? '✖' : '✏️' }}</span>
        <span v-if="!isPostFormVisible" class="edit-text">发帖</span>
        <span v-else>取消发帖</span>
      </button>
    </div>
    
    <!-- 发帖表单 -->
    <div v-if="isPostFormVisible" class="post-form-container">
      <form @submit.prevent="onPost" class="post-form">
        <div class="form-group">
          <label for="post-title">标题</label>
          <input 
            id="post-title"
            v-model="postForm.title" 
            type="text" 
            placeholder="请输入帖子标题" 
            required 
            class="form-control"
          />
        </div>
        <div class="form-group">
          <label for="post-content">内容</label>
          <textarea 
            id="post-content"
            v-model="postForm.content" 
            placeholder="请输入帖子内容..." 
            required 
            rows="6" 
            class="form-control"
          ></textarea>
        </div>
        <div class="form-actions">
          <button type="button" class="cancel-btn" @click="togglePostForm">取消</button>
          <button type="submit" class="submit-btn">发布帖子</button>
        </div>
      </form>
    </div>
    
    <!-- 帖子列表 -->
    <div class="posts-wrapper">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>正在加载帖子...</p>
      </div>
      
      <div v-else-if="currentList.length === 0" class="empty-state">
        <div class="empty-icon">📭</div>
        <h3>暂无帖子</h3>
        <p>快去互动吧！</p>
        <button class="post-btn" @click="togglePostForm">发布新帖</button>
      </div>
      
      <div v-else class="post-list">
        <div v-for="post in currentList" :key="post.id" class="post-card">
          <div class="post-meta">
            <div class="user-info">
              <div class="user-avatar">{{ post.username.charAt(0).toUpperCase() }}</div>
              <span class="user-name">{{ post.username }}</span>
            </div>
            <span class="post-time">{{ formatDate(post.created_at) }}</span>
          </div>
          
          <h3 class="post-title">{{ post.title }}</h3>
          <p class="post-content">{{ post.content }}</p>
          
          <div class="post-actions">
            <button class="action-btn" :class="{active: likeState[post.id]?.liked}" @click="toggleLike(post.id)">
              <span class="action-icon">👍</span>
              <span class="action-text">点赞({{ likeState[post.id]?.count || 0 }})</span>
            </button>
            <button class="action-btn" :class="{active: favState[post.id]?.favored}" @click="toggleFav(post.id)">
              <span class="action-icon">🔖</span>
              <span class="action-text">收藏({{ favState[post.id]?.count || 0 }})</span>
            </button>
            <button class="action-btn" @click="showComment(post.id)">
              <span class="action-icon">💬</span>
              <span class="action-text">评论({{ commentState[post.id]?.list.length || 0 }})</span>
            </button>
          </div>
          <div v-if="commentState[post.id] && commentState[post.id].show" class="comment-section">
            <div class="comment-list">
              <div v-for="c in commentState[post.id]?.list" :key="c.id" class="comment-item">
                <span class="comment-user">{{ c.username }}：</span>
                <span class="comment-content">{{ c.content }}</span>
                <span class="comment-time">{{ c.created_at }}</span>
              </div>
            </div>
            <div class="comment-input-row">
              <input v-model="commentState[post.id].input" class="comment-input" placeholder="写下你的评论..." />
              <button @click="submitComment(post.id)" class="comment-submit">发布</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const posts = ref([])
const likePosts = ref([])
const favPosts = ref([])
const commentPosts = ref([])
const tab = ref('all')
const loading = ref(true)
const router = useRouter()
const isPostFormVisible = ref(false)
const postForm = ref({ title: '', content: '' })

// 新增：点赞、收藏、评论状态
const user = JSON.parse(localStorage.getItem('user') || '{}')
const likeState = reactive({}) // {postId: {count, liked}}
const favState = reactive({})  // {postId: {count, favored}}
const commentState = reactive({}) // {postId: {list:[], show:false, input:''}}

const currentList = ref([])

// 切换发帖表单显示状态
const togglePostForm = () => {
  isPostFormVisible.value = !isPostFormVisible.value
  if (!isPostFormVisible.value) {
    postForm.value.title = ''
    postForm.value.content = ''
  }
}

// 发帖函数
const onPost = async () => {
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  if (!user.id) {
    alert('请先登录')
    router.push('/login')
    return
  }
  
  if (!postForm.value.title || !postForm.value.content) {
    alert('标题和内容不能为空')
    return
  }
  
  try {
    const res = await axios.post('/api/post', {
      user_id: user.id,
      title: postForm.value.title,
      content: postForm.value.content
    })
    
    const data = res.data
    if (data.code === 0) {
      alert('发帖成功')
      // 重置表单并隐藏
      postForm.value.title = ''
      postForm.value.content = ''
      isPostFormVisible.value = false
      
      // 刷新帖子列表
      fetchTabList()
    } else {
      alert(data.msg)
    }
  } catch (e) {
    alert('发帖失败，无法连接服务器')
  }
}

function switchTab(t) {
  tab.value = t
  fetchTabList()
}

async function fetchTabList() {
  loading.value = true
  if (tab.value === 'all') {
    await fetchPosts()
    currentList.value = posts.value
  } else if (tab.value === 'like') {
    if (!user.id) { currentList.value = []; loading.value = false; return }
    const res = await axios.get('/api/user-liked-posts', { params: { user_id: user.id } })
    likePosts.value = res.data.posts || []
    currentList.value = likePosts.value
  } else if (tab.value === 'fav') {
    if (!user.id) { currentList.value = []; loading.value = false; return }
    const res = await axios.get('/api/user-favored-posts', { params: { user_id: user.id } })
    favPosts.value = res.data.posts || []
    currentList.value = favPosts.value
  } else if (tab.value === 'comment') {
    if (!user.id) { currentList.value = []; loading.value = false; return }
    const res = await axios.get('/api/user-commented-posts', { params: { user_id: user.id } })
    commentPosts.value = res.data.posts || []
    currentList.value = commentPosts.value
  }
  loading.value = false
}

// 获取帖子列表并初始化点赞/收藏/评论状态
const fetchPosts = async () => {
  try {
    loading.value = true
    const res = await axios.get('/api/posts')
    const data = res.data
    if (data.code === 0) {
      posts.value = data.posts
      // 初始化点赞、收藏、评论状态
      for (const post of data.posts) {
        await fetchLikeState(post.id)
        await fetchFavState(post.id)
        if (!commentState[post.id]) {
          commentState[post.id] = { list: [], show: false, input: '' }
        }
        await fetchCommentList(post.id)
      }
    } else {
      alert('获取帖子失败：' + data.msg)
    }
  } catch (e) {
    alert('无法连接服务器')
  } finally {
    loading.value = false
  }
}

// 点赞相关
async function fetchLikeState(postId) {
  const res = await axios.get('/api/post-likes', { params: { post_id: postId, user_id: user.id } })
  likeState[postId] = { count: res.data.like_count, liked: res.data.liked }
}
async function toggleLike(postId) {
  if (!user.id) { alert('请先登录'); router.push('/login'); return }
  await axios.post('/api/like', { user_id: user.id, post_id: postId })
  await fetchLikeState(postId)
}

// 收藏相关
async function fetchFavState(postId) {
  const res = await axios.get('/api/post-favorites', { params: { post_id: postId, user_id: user.id } })
  favState[postId] = { count: res.data.fav_count, favored: res.data.favored }
}
async function toggleFav(postId) {
  if (!user.id) { alert('请先登录'); router.push('/login'); return }
  await axios.post('/api/favorite', { user_id: user.id, post_id: postId })
  await fetchFavState(postId)
}

// 评论相关
async function fetchCommentList(postId) {
  const res = await axios.get('/api/comments', { params: { post_id: postId } })
  commentState[postId].list = res.data.comments
}
function showComment(postId) {
  if (!commentState[postId]) {
    commentState[postId] = { list: [], show: false, input: '' }
  }
  commentState[postId].show = !commentState[postId].show
  if (commentState[postId].show) fetchCommentList(postId)
}
async function submitComment(postId) {
  if (!user.id) { alert('请先登录'); router.push('/login'); return }
  const content = commentState[postId].input.trim()
  if (!content) { alert('评论不能为空'); return }
  await axios.post('/api/comment', { user_id: user.id, post_id: postId, content })
  commentState[postId].input = ''
  await fetchCommentList(postId)
}

// 格式化日期显示
function formatDate(dateString) {
  const date = new Date(dateString)
  const now = new Date()
  const diffMs = now - date
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    const hours = date.getHours()
    const minutes = date.getMinutes()
    return `今天 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
  }
}

// 初始加载帖子
onMounted(() => {
  switchTab('all')
})
</script>

<style scoped>
.post-integrated-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.post-list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1.5rem;
}

.post-list-header h2 {
  font-size: 1.75rem;
  font-weight: 700;
  color: var(--neutral-800);
  margin: 0;
}

.post-btn {
  display: flex;
  align-items: center;
  background: transparent;
  color: var(--neutral-800);
  border: none;
  border-radius: var(--radius);
  padding: 0.6rem 1.25rem;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.post-btn:hover {
  color: var(--primary-color);
  transform: translateY(-2px);
}

.btn-icon {
  margin-right: 0.5rem;
}

.black-text {
  color: #000000;
}

/* 发帖表单样式 */
.post-form-container {
  background: white;
  border-radius: var(--radius-md);
  box-shadow: var(--shadow);
  margin-bottom: 2rem;
  overflow: hidden;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.post-form {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1.25rem;
}

.form-group label {
  display: block;
  font-weight: 600;
  color: var(--neutral-700);
  margin-bottom: 0.5rem;
}

.form-control {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid var(--neutral-300);
  border-radius: var(--radius);
  font-size: 1rem;
  transition: border-color 0.2s, box-shadow 0.2s;
  background-color: var(--neutral-50);
}

.form-control:focus {
  border-color: var(--primary-color);
  outline: none;
  box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.2);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
}

.cancel-btn {
  padding: 0.6rem 1.25rem;
  background: var(--neutral-200);
  color: var(--neutral-700);
  border: none;
  border-radius: var(--radius);
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background: var(--neutral-300);
}

.submit-btn {
  padding: 0.6rem 1.25rem;
  background: var(--success-color);
  color: #000000; /* 将颜色从白色改为黑色 */
  border: none;
  border-radius: var(--radius);
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.submit-btn:hover {
  background: var(--success-dark);
  transform: translateY(-2px);
}

/* 帖子列表样式 */
.posts-wrapper {
  min-height: 300px;
}

.loading-state, .empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem 0;
  color: var(--neutral-500);
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(58, 123, 213, 0.2);
  border-radius: 50%;
  border-top-color: var(--primary-color);
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.empty-state h3 {
  color: var(--neutral-700);
  margin-bottom: 0.5rem;
}

.empty-state p {
  margin-bottom: 1.5rem;
}

.post-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.post-card {
  background: white;
  border-radius: var(--radius-md);
  padding: 1.5rem;
  box-shadow: var(--shadow);
  transition: transform 0.2s, box-shadow 0.2s;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 0.875rem;
  margin-right: 0.5rem;
}

.user-name {
  font-weight: 600;
  color: var(--neutral-800);
}

.post-time {
  color: var(--neutral-500);
  font-size: 0.875rem;
}

.post-title {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 0.75rem;
  color: var(--neutral-800);
}

.post-content {
  color: var(--neutral-700);
  line-height: 1.6;
  margin-bottom: 1.5rem;
  white-space: pre-line;
}

.post-actions {
  display: flex;
  gap: 1rem;
  border-top: 1px solid var(--neutral-200);
  padding-top: 1rem;
}

.action-btn {
  display: flex;
  align-items: center;
  background: transparent;
  color: var(--neutral-600);
  border: none;
  padding: 0.5rem;
  font-size: 0.875rem;
  cursor: pointer;
  transition: color 0.2s;
}

.action-btn:hover {
  color: var(--primary-color);
  background: transparent;
}

.action-icon {
  margin-right: 0.375rem;
}

.action-btn.active {
  color: #2563eb;
  font-weight: 600;
}

.comment-section {
  background: #f7fafd;
  border-radius: 8px;
  margin-top: 1rem;
  padding: 1rem 1rem 0.7rem 1rem;
}

.comment-list {
  max-height: 180px;
  overflow-y: auto;
  margin-bottom: 0.7rem;
}

.comment-item {
  font-size: 0.97rem;
  margin-bottom: 0.4rem;
  color: #333;
}

.comment-user {
  color: #2563eb;
  font-weight: 600;
  margin-right: 0.3rem;
}

.comment-time {
  color: #aaa;
  font-size: 0.92rem;
  margin-left: 0.7rem;
}

.comment-input-row {
  display: flex;
  gap: 0.5rem;
  align-items: center;
  margin-bottom: 0.5rem;
}

.comment-input {
  flex: 1;
  border: 1px solid #dbeafe;
  border-radius: 6px;
  padding: 0.5rem 0.7rem;
  font-size: 0.97rem;
}

.comment-submit {
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 0.5rem 1.2rem;
  font-size: 0.97rem;
  cursor: pointer;
  transition: background 0.2s;
}

.comment-submit:hover {
  background: #1749b1;
}

.tab-group {
  display: flex;
  gap: 1rem;
  margin-right: 1.5rem;
}
.tab-group button {
  padding: 0.5rem 1.2rem;
  border: none;
  border-radius: var(--radius);
  background: var(--neutral-200);
  color: var(--neutral-700);
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}
.tab-group button.active {
  background: var(--primary-color);
  color: #60b2f1;
}

@media (max-width: 768px) {
  .post-integrated-container {
    padding: 1rem;
  }
  
  .post-list-header {
    margin-bottom: 1.5rem;
  }
  
  .post-list-header h2 {
    font-size: 1.5rem;
  }
  
  .post-btn {
    font-size: 0.875rem;
    padding: 0.5rem 1rem;
  }
  
  .post-form {
    padding: 1.25rem;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .cancel-btn, .submit-btn {
    width: 100%;
  }
  
  .post-card {
    padding: 1.25rem;
  }
}
</style>
